package com.springboot.mybatis.service.threaddemo;

/**
 * @author sunyt31481
 * @date 2020/8/6 10:16
 * @description 创建两个线程，轮流输出值，练习synchronized、wait和notifyAll的用法
 */

public class RunnableStyle
{
    public static void main(String[] args) {
        Object object = new Object();
        new Thread(new Number(object)).start();
        new Thread(new Character(object)).start();
    }
}

//创建数字线程，用实现Runnable接口的方式
class Number implements Runnable {
    private Object object;
    public Number(Object object) {
        this.object = object;
    }

    @Override
    public void run() {
        synchronized (object) {
            for (int i = 1; i <=26; i++) {
                System.out.print(i);
                object.notifyAll();
                try {
                    object.wait();
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

//创建字母线程
class Character implements Runnable {
    private Object object;
    public Character(Object object) {
        this.object = object;
    }

    @Override
    public void run() {
        synchronized (object) {
            for (char i = 'A'; i <= 'Z'; i++) {
                System.out.print(i);
                object.notifyAll();
                if (i < 'Z') {
                    try {
                        object.wait();
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
